package de.kardass.jsmatep.in;

import java.util.LinkedHashMap;
import java.util.Set;

public class DynamicValueObject extends LinkedHashMap<String, String> {
    
    private static final long serialVersionUID = -8638215830809966420L;
    
    private static final String MESSAGE_COLUMN_HEADER = "message";
    private static final Character DELIMITER = Character.valueOf(',');
    
    private String message;

    public String asCsvString() {
        return asCsvString(DELIMITER);
    }

    public String asCsvString(Character delim) {
        final StringBuilder builder = new StringBuilder();
        builder.append(keysAsCsvString(delim));
        builder.append(valuesAsCsvString(delim));
        return builder.toString();
    }
    
    public String valuesAsCsvString() {
        return valuesAsCsvString(DELIMITER);
    }

    public String valuesAsCsvString(Character delim) {
        final StringBuilder builder = new StringBuilder();
        final Set<String> keys = keySet();
        boolean firstAdded = false;
        String value;
        for (String aKey : keys) {
            if (firstAdded) {
                builder.append(delim);
            }
            firstAdded = true;
            value = get(aKey);
            builder.append(value == null ? "" : value);
        }
        if (message != null && message.trim().length() > 0) {
            if (firstAdded) {
                builder.append(delim);
            }
            builder.append(message);
        }
        return builder.toString();
    }

    public String keysAsCsvString() {
        return keysAsCsvString(DELIMITER);
    }
    
    public String keysAsCsvString(Character delim) {
        final StringBuilder builder = new StringBuilder();
        final Set<String> keys = keySet();
        boolean firstAdded = false;
        for (String aKey : keys) {
            if (firstAdded) {
                builder.append(delim);
            }
            firstAdded = true;
            builder.append(aKey);
        }
        if (message != null && message.trim().length() > 0) {
            if (firstAdded) {
                builder.append(delim);
            }
            builder.append(MESSAGE_COLUMN_HEADER);
        }
        return builder.toString();
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "DynamicValueObject [" + MESSAGE_COLUMN_HEADER + "=" + message + ", " + super.toString() + "]";
    }
 
}
